package exercise.jslide.jslide.controller;

import java.io.*;

import exercise.jslide.jslide.app.AppContext;
import exercise.jslide.jslide.model.Presentation;
import exercise.jslide.jslide.model.SlideElement;
import exercise.jslide.jslide.model.image.ImageElement;
import exercise.jslide.jslide.utils.FileUtils;
import exercise.jslide.jslide.utils.SerializationUtils;
import javafx.scene.image.Image;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.nio.file.Files;
import java.nio.file.Paths;

import javafx.scene.control.TextField;

public class FileController {
    private AppContext appContext;
    private Stage primaryStage;

    public FileController(Stage primaryStage) {
        this.appContext = AppContext.getInstance();
        this.primaryStage = primaryStage;
    }

    public void savePresentation() {
        String filePath = appContext.getCurrentPresentation().getFilePath();
        if (filePath == null) {
            saveAsPresentation();
        } else {
            try {
                //序列化，将对象写入文件中，文件名为JSLIDEPRESENTATION.JSLIDE
                SerializationUtils.serialize(appContext.getCurrentPresentation(),
                        new File(appContext.getCurrentPresentation().getPresentationTempFilePath() + File.separator + "JSLIDEPRESENTATION.JSLIDE"));

                //将文件夹打包成zip文件，文件名为演示文稿的标题，后缀为.jslide
                FileUtils.zipFileTree(new File(appContext.getCurrentPresentation().getPresentationTempFilePath()), new File(filePath + File.separator + appContext.getCurrentPresentation().getPresentationTitle() + ".jslide"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void openPresentation() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("打开JSlide演示文稿");
        fileChooser.getExtensionFilters().add(
                new FileChooser.ExtensionFilter("JSlide Files", "*.jslide")
        );

        File file = fileChooser.showOpenDialog(primaryStage);
        if (file != null) {
            try {
                Presentation presentation = new Presentation();
                String TempPath = FileUtils.createTempDirectory(presentation.getPresentationTitle()).getAbsolutePath();
                FileUtils.unzip(file.getCanonicalPath(), TempPath);
                presentation.setPresentationTitle(FileUtils.getFileNameWithoutExtension(file.getName()));

                //反序列化，将文件中的对象读取出来，文件名为JSLIDEPRESENTATION.JSLIDE，解决文件重命名后不能打开的问题
                presentation = (Presentation) SerializationUtils.deserialize(new File(presentation.getPresentationTempFilePath()
                        + File.separator + "JSLIDEPRESENTATION.JSLIDE"));

                //设置演示文稿的临时文件路径
                presentation.setPresentationTempFilePath(TempPath);

                //设置演示文稿的文件路径
                presentation.setPresentationFilePath(file.getAbsolutePath().replace(file.getName(), ""));

                //设置当前演示文稿
                appContext.setCurrentPresentation(presentation);

                for (int i = 0; i < presentation.getSlides().size(); i++) {
                    for (SlideElement slideElement:  presentation.getSlides().get(i).getElements()){
                        if(slideElement!=null && slideElement.getClass()== ImageElement.class){
                            ImageElement imageElement = (ImageElement) slideElement;
                            imageElement.setFilePath(presentation.getPresentationTempFilePath() +  File.separator+"images/"+ File.separator);
                        }
                    }
                }
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    public void saveAsPresentation() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("保存JSlide演示文稿");
        fileChooser.getExtensionFilters().add(
                new FileChooser.ExtensionFilter("JSlide Files", "*.jslide")
        );

        File file = fileChooser.showSaveDialog(primaryStage);
        if (file != null) {
            try {
                //设置演示文稿的标题
                appContext.getCurrentPresentation().setPresentationTitle(FileUtils.getFileNameWithoutExtension(file.getName()));

                //设置演示文稿的文件路径，解决另存为后不能直接保存的问题
                appContext.getCurrentPresentation().setPresentationFilePath(file.getAbsolutePath().replace(file.getName(), ""));

                //序列化，将对象写入文件中，文件名为JSLIDEPRESENTATION.JSLIDE，解决文件重命名后不能打开的问题
                SerializationUtils.serialize(appContext.getCurrentPresentation(),
                        new File(appContext.getCurrentPresentation().getPresentationTempFilePath() + File.separator + "JSLIDEPRESENTATION.JSLIDE"));

                //将文件夹打包成zip文件，文件名为演示文稿的标题，后缀为.jslide
                FileUtils.zipFileTree(new File(appContext.getCurrentPresentation().getPresentationTempFilePath()), file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //这里给出一个基本思路：首先选择指定路径的文件，然后将这个文件复制一份到当前文件所在的目录，相对路径，之后在显示图片时调用当前目录底下的文件即可
    public FileChooser createImageChooser() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("Image files (*.png,*.jpg)", "*.png", "*.jpg"),
                new FileChooser.ExtensionFilter("ALL files (*.*)", "*.*")
        );
        return fileChooser;

    }


    private String targetPath = "/images/";
    private TextField fileNameField = new TextField();

    public String openImageToSlide() {

        FileChooser fileChooser = createImageChooser();
        File selectedfile = fileChooser.showOpenDialog(primaryStage);
        if (selectedfile != null) {
            String fileName = System.currentTimeMillis() + selectedfile.getName();
            String targetFile = appContext.getCurrentPresentation().getPresentationTempFilePath() + targetPath + fileName;
            try {
                //将选中目标复制到相对路径中
                Files.copy(selectedfile.toPath(), Paths.get(targetFile));
                fileNameField.setText(fileName);
                return fileName;
                //尝试在文件中打开图片
//                Image image = new Image(targetFile);
//                imageView.setImage(image);
//                VBox root = new VBox(fileNameField, imageView);
//                primaryStage.setScene(new Scene(root, 400, 300));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;

    }
}




